$(function () {
    // 图片预览 鼠标进入事件，鼠标进入标签，把当前标签的imageurl赋给mainimage
    $(document).on("mouseenter",".p-img-item",function () {
        var imageURL = $(this).find(".p-img").attr("src");
        $(".main-img").attr("src",imageURL);
    });
    // count 判断并获取当前的class，获取最大库存和初始库存，判断上面取得class是plus则加上一，反之亦然。
    $(document).on("click",".p-count-btn",function () {
        var type = $(this).hasClass("plus") ? "plus" : "minus",
            $pCount = $(".p-count"),
            currentCount = parseInt($pCount.val()),
            minCount = 1,
            maxCount = $(".p-stock-con").find(".info").attr("value") || 1;
        if (type === "plus"){
            $pCount.val(currentCount < maxCount ? currentCount + 1 : maxCount);
        }else if (type === "minus") {
            $pCount.val(currentCount > minCount ? currentCount - 1  : minCount)
        }
    });

    var data = {
        productId : $(".productId").val(),
        quantity : $(".p-count").val()
    };
    // 加入购物车
    $(document).on("click",".cart-add",function () {
        $.ajax({
            type: 'POST',
            url: '/cart_add',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (result) {
                if (result.resultCode == 200){
                    swal({
                        title:"添加购物车成功",
                        text:"是否跳转到购物车",
                        icon: "success",
                        buttons: true,
                    }).then((flag) => {
                        if (flag){
                            window.location.href = "/cart_list";
                        }
                    });
                }else {
                    swal('加入购物车失败',{
                        icon: 'error'
                        });
                }
            }
        })
    })
})


